/** ###################################################################
**     Filename  : Fonera.C
**     Project   : Motologger_v2
**     Processor : MC9S12XA256CFU
**     Compiler  : CodeWarrior HCS12X C Compiler
**     Date/Time : 12/7/2009, 5:48 PM
**     Contents  :
**         User source code
**
**     (c) Copyright UNIS, a.s. 1997-2008
**     UNIS, a.s.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/


/* MODULE Fonera */
#include "Wifi_SCI.h"
#include "stddef.h"
#include "Fonera.h"
#include "gps.h" //for LF def

unsigned char Fonera_RxBuff[RXBUFFSZ];
volatile unsigned char Fonera_DataSize=0;
volatile unsigned char Fonera_DataReady=0;

unsigned char Fonera_GetFlag(){
	return Fonera_DataReady;	
}
void Fonera_SetFlag(){
  Fonera_DataReady = 1;
}
void Fonera_ClearFlag(){
	
	 Fonera_DataReady = 0;
}

void convert_4to8(char *input, char* output, int input_size, int output_size){
       
       int i;
       char *temp_out;
       temp_out = output;
       for(i=0;i<input_size&&temp_out<(output+output_size-1);i+=2){
               *temp_out=input[i]+((input[i+1]>>4)&0x0F);
                temp_out++;
       }
}


void Fonera_Send(char* data, short size){
	int i=1;
	while (Wifi_SCI_SendChar(*(data)) == ERR_TXFULL){}
	for(;i<size;i++){
		while (Wifi_SCI_SendChar(data[i]&0xF0) == ERR_TXFULL){}
		while (Wifi_SCI_SendChar((data[i]&0x0F)<<4) == ERR_TXFULL){}
	}
	while (Wifi_SCI_SendChar(LF) == ERR_TXFULL){}

}

 short Fonera_Receive(char* data, short size){
	int rval= (Fonera_DataSize-2)/2;
	rval=(rval>size?size:rval);
	if(Fonera_GetFlag()==0)
		return 0;
	convert_4to8(Fonera_RxBuff+1, data+1, Fonera_DataSize-2, size);
	data[0]=Fonera_RxBuff[0];
	
	//clear flag
	Fonera_ClearFlag();
	//reset index
	Fonera_DataSize=0;
	
	return rval;
	
}
  




void Fonera_BufferData(char data){
    if(Fonera_GetFlag()|CR==data) { //not done reading from buffer
    	return;
    } 
    else {  //may need to look for start token...
      Fonera_RxBuff[Fonera_DataSize] = data; //buffer for gps data
      if(Fonera_RxBuff[Fonera_DataSize] == LF) { 
        Fonera_SetFlag(); 
      } 
      else{
        Fonera_DataSize++;  
      }
    }
    
     
}


/* END Fonera */
